package com.archives.blog.manager.impl;

import com.archives.blog.manager.ArticleManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.archives.blog.common.domain.dao.ArticleChannelRepository;
import com.archives.blog.common.domain.dao.ArticleRepository;
import com.archives.blog.common.domain.entity.Article;
import com.archives.blog.common.domain.entity.ArticleChannel;
import com.archives.blog.common.domain.pojo.request.ArticleAddRequest;
import com.archives.blog.common.domain.pojo.request.ArticleModifyRequest;
import com.archives.blog.common.domain.pojo.request.ArticleQueryRequest;
import com.archives.blog.common.enums.ErrorCodeEnum;
import com.archives.blog.common.exp.BlogException;

@Service
public class ArticleManagerImpl implements ArticleManager {
	
	@Autowired
	private ArticleRepository articleRepository;
	
	@Autowired
	private ArticleChannelRepository articleChannelRepository;

	@Override
	public Article getDetail(Long id) {
		return articleRepository.getOne(id);
	}
	
	@Override
	public void add(ArticleAddRequest request) {
		ArticleChannel channel = articleChannelRepository.findOne(request.getChannelId());
		if (channel == null) {
			throw new BlogException(ErrorCodeEnum.DATA_ILLEGAL, "分类不存在");
		}
		Article article = new Article();
		article.add(request, channel);
		articleRepository.save(article);
	}

	@Override
	public void modify(ArticleModifyRequest request) {
		ArticleChannel channel = articleChannelRepository.findOne(request.getChannelId());
		if (channel == null) {
			throw new BlogException(ErrorCodeEnum.DATA_ILLEGAL, "分类不存在");
		}
		Article article = articleRepository.findOne(request.getArticleId());
		if (article == null) {
			throw new BlogException(ErrorCodeEnum.DATA_ILLEGAL, "文章不存在");
		}
		article.modify(request, channel);
		articleRepository.save(article);
	}

	@Override
	public void delete(Long id) {
		articleRepository.delete(id);
	}

	@Override
	public Page<Article> getPage(ArticleQueryRequest request) {
		Pageable pageable = new PageRequest(request.getPageIndex(), request.getPageSize());
		Article probe = new Article();
		probe.setAuthor(request.getAuthor());
		probe.setChannelId(request.getChannelId());
		probe.setTitle(request.getTitle());
		probe.setKeywords(request.getKeywords());
		probe.setIntro(request.getIntro());
		Example<Article> example = Example.of(probe);
		Page<Article> page = articleRepository.findAll(example, pageable);
		return page;
	}

}
